from django.db import models

from user.models import User
from utils.tools import get_now, json_to_dl, dl_to_json

# Create your models here.
class Questionnaire(models.Model):
	id = models.AutoField(verbose_name="id", primary_key=True, unique=True)
	title = models.TextField(verbose_name="标题", null=False)
	content = models.TextField(verbose_name="问卷内容", null=False)
	create_time = models.CharField(verbose_name="创建时间", max_length=255, null=True)
	
	def get_content(self):
		return json_to_dl(self.content or "{}")
	
	def create(self):
		self.create_time = get_now()
		self.save()
	
	class Meta:
		verbose_name = "问卷"  # 模型名称
		verbose_name_plural = "问卷列表"  # 模型复数名称
	
	def __str__(self):
		return str(self.title)
	
class Psychometry(models.Model):
	id = models.AutoField(verbose_name="id", primary_key=True, unique=True)
	user = models.ForeignKey(to=User, to_field="uid", on_delete=models.CASCADE)
	questionnaire = models.ForeignKey(to=Questionnaire, to_field="id", on_delete=models.CASCADE)
	answer = models.TextField(verbose_name="选择答案", null=True)
	analysis = models.TextField(verbose_name="结果分析", null=True)
	create_time = models.CharField(verbose_name="创建时间", max_length=255, null=True)
	answer_time = models.CharField(verbose_name="答题时间", max_length=255, null=True)
	
	def get_analysis(self):
		return json_to_dl(self.analysis or "{}")
	
	def create(self):
		self.create_time = get_now()
		self.save()
	
	def answer_questions(self, answer, analysis):
		self.answer = dl_to_json(answer)
		self.analysis = dl_to_json(analysis)
		self.answer_time = get_now()
		self.save()
	
	class Meta:
		verbose_name = "测试"  # 模型名称
		verbose_name_plural = "测试列表"  # 模型复数名称
	
	def __str__(self):
		return f"{self.questionnaire}-{self.user}-{self.create_time}"


class Analysis(models.Model):
	id = models.AutoField(verbose_name="id", primary_key=True, unique=True)
	qid = models.ForeignKey(to=Questionnaire, to_field="id", on_delete=models.CASCADE)
	code = models.IntegerField(verbose_name="识别码", null=False)
	title = models.CharField(verbose_name="标题", max_length=255, null=False)
	range = models.CharField(verbose_name="范围", max_length=255, null=True)
	explain = models.TextField(verbose_name="解释", null=True)
	suggest = models.TextField(verbose_name="建议", null=True)
	
	class Meta:
		verbose_name = "测试"  # 模型名称
		verbose_name_plural = "测试列表"  # 模型复数名称
	
	def __str__(self):
		return f"{self.code}"